#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace AbstractClass.Runtime.Serialization
{
    /// <summary>
    /// Represents a type to binary (de)serialize an object which implements <see cref="IBObject"/>.
    /// </summary>
    /// <typeparam name="T">The type to (de)serialize which implements <see cref="IBObject"/>.</typeparam>
    public static class BObjectSerializer<T> where T : IBObject, new()
    {
        private static BinaryFormatter _binaryFormatter;

        /// <summary>
        /// Deserializes an object of type <typeparamref name="T"/> from a binary file.
        /// </summary>
        /// <param name="file">Binary file path.</param>
        /// <returns>Deserialized object of type <typeparamref name="T"/>.</returns>
        public static T ReadFile(string file)
        {
            return ReadFile(file, string.Empty);
        }

        /// <summary>
        /// Deserializes an object of type <typeparamref name="T"/> from an encrypted binary file.
        /// </summary>
        /// <param name="file">Binary file path.</param>
        /// <param name="password">Password to decrypt the stream.</param>
        /// <returns>Deserialized object of type <typeparamref name="T"/>.</returns>
        public static T ReadFile(string file, string password)
        {
            T bObj;
            _binaryFormatter = new BinaryFormatter {SurrogateSelector = new SurrogateSelector()};
            _binaryFormatter.SurrogateSelector.ChainSelector(new NonSerialiazableTypeSurrogateSelector());

            using (var stream = new FileStream(file, FileMode.OpenOrCreate))
            {
                Stream buffer = !string.IsNullOrEmpty(password) ? Security.Decrypt(stream, password) : stream;
                try
                {
                    using (buffer)
                    {
                        bObj = (T) _binaryFormatter.Deserialize(buffer);
                        bObj.Init();
                    }
                }
                catch (SerializationException ex)
                {
                    Trace.WriteLine(ex);
                    bObj = new T();
                }
            }

            return bObj;
        }

        /// <summary>
        /// Serializes an object of type <typeparamref name="T"/> to a binary file.
        /// </summary>
        /// <param name="file">Binary file path.</param>
        /// <param name="bObj">An object of type <typeparamref name="T"/> to serialize.</param>
        /// <returns><c>true</c> if operation is successful; otherwise, <c>false</c>.</returns>
        public static bool WriteFile(string file, T bObj)
        {
            return WriteFile(file, bObj, string.Empty);
        }

        /// <summary>
        ///  Serializes an object of type <typeparamref name="T"/> to a binary file, optionally encrypts the file.
        /// </summary>
        /// <param name="file">Binary file path.</param>
        /// <param name="bObj">An object of type <typeparamref name="T"/> to serialize.</param>
        /// <param name="password">Password to encrypt the stream.</param>
        /// <returns><c>true</c> if operation is successful; otherwise, <c>false</c>.</returns>
        public static bool WriteFile(string file, T bObj, string password)
        {
            bool result = false;
            _binaryFormatter = new BinaryFormatter {SurrogateSelector = new SurrogateSelector()};
            _binaryFormatter.SurrogateSelector.ChainSelector(new NonSerialiazableTypeSurrogateSelector());

            using (var stream = new FileStream(file, FileMode.Create))
            {
                try
                {
                    bObj.Close();
                    Stream buffer = !string.IsNullOrEmpty(password) ? Security.Encrypt(stream, password) : stream;

                    using (buffer)
                    {
                        _binaryFormatter.Serialize(buffer, bObj);
                    }
                    result = true;
                }
                catch (SerializationException ex)
                {
                    Trace.WriteLine(ex);
                }
            }
            return result;
        }
    }
}